package gui

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
	"strconv"
	"strings"
	"time"
	"treesize/src/org/ligson/treesize/util"
)

func delFile(destPath string) {
	if util.IsDir(destPath) {
		var subFiles []string
		for _, node := range myFileMap {
			var path string = node.Path
			if strings.HasPrefix(path, destPath) {
				subFiles = append(subFiles, path)
			}
		}
		var subDirs []string
		//先删除文件
		for _, file := range subFiles {
			if !util.IsDir(file) {
				logrus.Info("删除文件:" + file)
				util.DeleteFile(file)
			} else {
				subDirs = append(subDirs, file)
			}
		}
		//删除目录
		var maxLevel int = 0
		var minLevel int = 0
		for _, dir := range subDirs {
			file := myFileMap[dir]
			if file.Level > maxLevel {
				maxLevel = file.Level
			}

			if file.Level < minLevel {
				minLevel = file.Level
			}
		}
		for i := maxLevel; i >= minLevel; i-- {
			logrus.Info("删除第" + strconv.Itoa(i) + "级目录")
			for _, dir := range subDirs {
				if myFileMap[dir].Level == i {
					logrus.Info("删除第" + strconv.Itoa(i) + "级目录:" + dir)
					util.DeleteFile(dir)
				}
			}
		}
	} else {
		logrus.Info("删除文件:" + destPath)
		util.DeleteFile(destPath)
	}
}
func deleteMenunOnClick(tl *TreeLabel) {
	startTime := time.Now().UnixMilli()
	loadingDlg := dialog.NewInformation("提示", tl.Path+"删除中...", w)
	loadingDlg.Show()
	delFile(tl.Path)
	loadingDlg.Hide()
	endTime := time.Now().UnixMilli()
	dlg := dialog.NewInformation("提示", tl.Path+"删除中花费时间(s):"+util.TruncDecimal(float64((endTime-startTime)/1000.0), 2), w)
	dlg.Show()
	loadData(dirLabel.Text, myFileTree)
}
func showContextMenu(tl *TreeLabel, e *fyne.PointEvent, w fyne.Window) {
	logrus.Info(tl.Text)

	item := fyne.NewMenuItem("删除", func() {
		deleteMenunOnClick(tl)
	})
	delEmptyItem := fyne.NewMenuItem("删除空目录", func() {
		for _, info := range myFileMap {
			if info.File.IsDir() {
				if util.IsEmptyDir(info.Path) {
					util.DeleteFile(info.Path)
				}
			}
		}
		dialog.NewInformation("提示", "删除完成", w).Show()
		loadData(dirLabel.Text, myFileTree)
	})
	menu := fyne.NewMenu("", item, delEmptyItem)
	widget.ShowPopUpMenuAtPosition(menu, w.Canvas(), e.AbsolutePosition)
}
